<template>
  <div>
    <!-- http-request 覆盖默认的上传行为，可以自定义上传的实现 -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="circle" :percentage="percent" />
    </el-upload>
  </div>
</template>

<script>
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDTlnY2HH0SdXCaXDdojNnwqTpujIbgU1H', // id
  SecretKey: '2mGSO3RYOyHJ4ZomUw83h4B1asuf9MI3' // 密匙
})
export default {
  props: {
    value: { type: String, default: '' }
  },
  data() {
    return {
      percent: 0,
      showProgress: false
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/webp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,png,webp 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(res) {
      if (res.file) {
        this.showProgress = true
        cos.putObject({
          Bucket: 'shizhiqiniubi-1307943198', /* 必须 */
          Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名称 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => { // 上传进度
            this.percent = progressData.percent * 100
            console.log(this.percent)
          }
        }, (err, data) => {
        // err	请求发生错误时返回的对象，包括网络错误和业务错误。如果请求成功则为空
          // data	请求成功时返回的对象，如果请求发生错误，则为空
          console.log('err, data', err, data)
          setTimeout(() => {
            this.showProgress = false
          }, 500)
          if (data.statusCode === 200) {
            const imageUrl = `https:${data.Location}`
            this.$emit('input', imageUrl)
          }
        })
      } // 覆盖默认的上传行为，可以自定义上传的实现
    } }
}
</script>
<style>
  .el-progress {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
